package com.dong.aoptools.view.handlerview;

import com.dong.aoptools.constant.PropertiesConst;
import com.dong.aoptools.util.PropertiesUtils;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: 陈瑞东
 * @create: 2021-11-29 16:58
 */
public class OutputLoadedClassHandlerView extends CommonHandlerView {
    @Override
    public CommonHandlerView subInit() {
        // 设置布局
        CommonHandlerView container = this;
        GridBagLayout manager = new GridBagLayout();
        container.setLayout(manager);
        GridBagConstraints gbc = new GridBagConstraints();

        Map<String, JTextField> param = new HashMap<>();

        // 设置页面
        gbc.insets = new Insets(10, 10, 10, 10);
        for (Map.Entry<String, String> entry : PropertiesConst.CONFIG_OUTPUT_KEY_DESC.entrySet()) {
            String key = entry.getKey();
            String desc = entry.getValue();
            String value = PropertiesUtils.getConfigProperty(key, "");

            gbc.weightx = 0;
            gbc.fill = GridBagConstraints.NONE;
            gbc.gridwidth = GridBagConstraints.RELATIVE;
            JLabel jLabel = new JLabel(desc + "：");
            manager.setConstraints(jLabel, gbc);

            gbc.weightx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            JTextField jTextField = new JTextField(value,20);
            manager.setConstraints(jTextField, gbc);

            container.add(jLabel);
            container.add(jTextField);

            param.put(key, jTextField);
        }

        JButton selectPath = new JButton("选择路径");
        container.add(selectPath);
        // 添加按钮监听事件
        selectPath.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("选择类存储路径");
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            fileChooser.setCurrentDirectory(new File("./"));

            fileChooser.showOpenDialog(this);

            if (fileChooser.getSelectedFile() == null) {
                return;
            }
            // 设置路径
            param.get(PropertiesConst.CONFIG_FIELD_OUTPUT_PATH).setText(fileChooser.getSelectedFile().getAbsolutePath());
        });

        JButton jButton = new JButton("保存");
        manager.setConstraints(jButton, gbc);
        container.add(jButton);

        // 添加事件
        jButton.addActionListener(e -> {
            for (Map.Entry<String, JTextField> entry : param.entrySet()) {
                PropertiesUtils.setConfigProperty(entry.getKey(), entry.getValue().getText());
            }
            JOptionPane.showMessageDialog(this, "保存成功！");
        });

        return container;
    }
}
